package com.plian.system.service.sys.file;

import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.enumeratea.TemplateDemoType;
import com.plian.system.pdf.OutPdf;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class TemplateDemoService {
    public void exportTemplateExcel(HttpServletResponse response, OutputStream os, String formType) {
        try {
            TemplateDemoType templateType;
            try {
                String constantName;
                //如果一个模块有多张表按照年份区分type为formtype-年份后两位
                if(formType.contains("-")){
                    int formTypeConstant = Integer.parseInt(formType.split("-")[0]);
                    String year = formType.split("-")[1];
                    constantName = getConstantName(formTypeConstant) + year;
                }else {
                    int formTypeConstant = Integer.parseInt(formType);
                    constantName = getConstantName(formTypeConstant);
                }
                templateType = TemplateDemoType.valueOf(constantName);
            } catch (IllegalArgumentException e) {
                templateType = TemplateDemoType.valueOf(formType);
            }
            String fname = templateType.getFileName();
            InputStream inputStream = this.getClass().getResourceAsStream(templateType.getFilePath());
            os = response.getOutputStream(); // 取得输出流
            response.reset(); // 清空输出流
            response.setCharacterEncoding("UTF-8"); // 设置相应内容的编码格式
            fname = java.net.URLEncoder.encode(fname, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fname.getBytes("UTF-8"), "UTF-8") + ".xlsx");
            response.setContentType("application/msexcel");

            int len;
            byte[] b = new byte[2048];
            while ((len = inputStream.read(b)) != -1) {
                os.write(b, 0, len);
            }
            response.setHeader("Content-Length", String.valueOf(inputStream.available()));

            inputStream.close();
            os.close();
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
    }

    public File buildpdf(HttpServletResponse response,String type) {
        File file = null;

        try {
            TemplateDemoType templateType = TemplateDemoType.valueOf(type);
            if (templateType.getFileName().endsWith(".pdf")) {
                Map<String, Object> data = new HashMap<>(16);
                InputStream inputStream = this.getClass().getResourceAsStream(templateType.getFilePath());
                // 通过将文件转换为临时文件进行操作
                File model = File.createTempFile("template", ".pdf");
                try {
                    assert inputStream != null;
                    FileUtils.copyInputStreamToFile(inputStream, model);
                } finally {
                    // 关闭IO
                    IOUtils.closeQuietly(inputStream);
                }
                file = OutPdf.createPdf(model, data, templateType.getFileName());
            }else if (templateType.getFileName().endsWith(".docx")){
                InputStream docxStream = this.getClass().getResourceAsStream(templateType.getFilePath());
                // 通过将文件转换为临时文件进行操作
                File model = File.createTempFile("template", ".docx");
                try {
                    assert docxStream != null;
                    FileUtils.copyInputStreamToFile(docxStream, model);
                } finally {
                    // 关闭IO
                    IOUtils.closeQuietly(docxStream);
                }

                String encodedFileName = URLEncoder.encode(templateType.getFileName(), StandardCharsets.UTF_8.toString());
                response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);                response.setContentLengthLong(model.length());
                try (InputStream inputStream = Files.newInputStream(model.toPath());
                     OutputStream os = response.getOutputStream()) {
                    byte[] b = new byte[2048];
                    int length;
                    while ((length = inputStream.read(b)) > 0) {
                        os.write(b, 0, length);
                    }
                    os.flush();
                }
            }

        }  catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return file;
    }

    public static String getConstantName(int value) {
        Field[] fields = FormTypeConstant.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                if (field.getInt(null) == value) {
                    return field.getName();
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
